package com.fywsy.fyweb.strategy;

import com.fywsy.fyweb.entity.SendItem;
import com.fywsy.fyweb.utils.RestTemplateUtil;
import com.fywsy.fyweb.utils.TextUtils;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 江湖大侠
 *
 *
 * 游戏后台实现类
 * 注解gameId对应数据库游戏id
 * 注解GongnengMethod对应数据库功能id
 */
@Component
@GameId(2)
public class JianghudaxiaStrategy extends BaseGameStrategy {
    public static final String GMCODE = "diyao88";
    public static final String GET_GUID = "http://114.66.45.141:30850/api/verify";
    public static final String MAIL = "http://114.66.45.141:30850/api/send-mail";
    public static final String CLEAR_BAG = "http://114.66.45.141:30850/api/clear";

    /**
     * {"guid":"0000000103F2000100000003","items":"4:2:2,1,0,0;"}
     * @param item
     * @return
     */
    @GongnengMethod(201)
    public String mail(SendItem item) {
        String guid = getGuid(item.uid);
        if(TextUtils.isEmpty(guid)) return "角色不存在";
        /**
         * 物品id> 120000的 需要加个1，
         */
        long itemId = Long.parseLong(item.itemId);
        String wupin = "4:2:" + (itemId >= 120000 ? "1," : "") + item.itemId + "," + item.number + ",0,0";

        Map<String,String> params = new HashMap<>();
        params.put("guid",guid);
        params.put("items",wupin);
        String s = RestTemplateUtil.sendPostJsonAndGetJsonKey(MAIL, params, "success");
        return "true".equals(s) ? "发送成功" : "发送失败";
    }

    @GongnengMethod(203)
    public String clearBag(SendItem item) {
        String guid = getGuid(item.uid);
        if(TextUtils.isEmpty(guid)) return "角色不存在";

        Map<String,String> params = new HashMap<>();
        params.put("guid", guid);

        RestTemplateUtil.sendPostJsonAndGetJsonKey(CLEAR_BAG, params,"success");
        return "清理成功，请重新上线";
    }

    /**
     * 通过编号获取真实id
     * {"verifyCode":"diyao88","roleId":"000001000036"}
     * @param uid
     * @return
     */
    public String getGuid(String uid) {
        Map<String,String> params = new HashMap<>();
        params.put("verifyCode",GMCODE);
        params.put("roleId",uid);
        String response = RestTemplateUtil.sendPostJson(GET_GUID, params);
        try {
            // 解析响应
            JsonObject jsonResponse = JsonParser.parseString(response).getAsJsonObject();
            return jsonResponse.get("guid").getAsString();
        } catch (Exception e) {
            return "";
        }
    }

    public static void main(String[] args) {
        SendItem item = new SendItem();
        item.uid = "000001000017";
        item.number = "2";
        item.itemId = "122005";
        System.out.println(new JianghudaxiaStrategy().mail(item));
    }
}

